import 'dart:async';

import 'package:flutter/material.dart';

///zhudaihao
///2024-1-30
///获取验证码
class VerificationCodeButton extends StatefulWidget {
  ///倒计时时间
  final int? currentTime;

  ///点击按钮回调
  final Function? onClick;

  const VerificationCodeButton({this.currentTime, this.onClick, Key? key})
      : super(key: key);

  @override
  State<VerificationCodeButton> createState() => _VerificationCodeButtonState();
}

class _VerificationCodeButtonState extends State<VerificationCodeButton> {
  var codeText = "";

  ///记录倒计时颜色
  var codeColorTag = const Color(0xff1157FF);

  Timer? _countDownTimer;
  late int _currentTime;

  @override
  void initState() {
    _currentTime = widget.currentTime ?? 60;
    codeText = '获取验证码';
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return InkWell(
      child: Container(
        width: 92,
        height: 46,
        alignment: Alignment.center,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(8),
          border: Border.all(color: const Color(0xff1157FF), width: 1),
        ),
        child: RepaintBoundary(
          child: Text(
            codeText,
            style: TextStyle(color: codeColorTag, fontSize: 14),
          ),
        ),
      ),
      onTap: () {
        if (_currentTime == 60) {
          if (widget.onClick != null) {
            widget.onClick!();
          }
          _startTimeCountDown();
        }
      },
    );
  }

  ///倒计时
  void _startTimeCountDown() {
    if (_countDownTimer != null) {
      _countDownTimer?.cancel();
      _countDownTimer = null;
    }
    _countDownTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (timer.tick == 60) {
        codeColorTag = const Color(0xff1157FF);
        _currentTime = 60;
        codeText = 'get_code';
        _countDownTimer?.cancel();
        _countDownTimer = null;
      } else {
        codeColorTag = const Color(0xffDFE0E7);
        _currentTime--;
        codeText = '${_currentTime}S';
      }

      setState(() {});
    });
  }
}
